package cn.edu.ujn.finallab.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.ujn.finallab.dao.Admin;
import cn.edu.ujn.finallab.dao.Customer;

public class LoginInterceptor implements HandlerInterceptor {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取路径
        String url = request.getRequestURI();  
        // 如果是以下路径就不用拦截
        if(url.indexOf("/customerLogin")>=0 || url.indexOf("/index")>=0 || url.indexOf("/adminLogin")>=0 || url.indexOf("/register")>=0 || url.indexOf("/customerLogout")>=0 || url.indexOf("/adminExit")>=0 || url.indexOf("/submitRegister")>=0){  
        	return true;  
		}  
		HttpSession session = request.getSession();  
		// 判断用户或者管理员有没有登录
		Customer customer = (Customer) session.getAttribute("user");
		Admin admin = (Admin) session.getAttribute("admin");
		if(customer != null){
			return true;  
		} else if(admin != null){
			return true;
		}
		// 判断用户session失效前是用户登录还是管理员登录
		if(url.indexOf("/customerLogin")>=0) {
	        request.setAttribute("msg", "您还没有登录，请先登录！");
	        request.getRequestDispatcher("index.jsp").forward(request, response);
	        return false;
		} else if(url.indexOf("/adminLogin")>=0) {
	        request.setAttribute("msg", "您还没有登录，请先登录！");
	        request.getRequestDispatcher("adminLogin.jsp").forward(request, response);
	        return false;
		} else {
			request.setAttribute("msg", "您还没有登录，请先登录！");
	        request.getRequestDispatcher("index.jsp").forward(request, response);
	        return false;
		}
        
    }	


	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
